package com.example.common.service.impl;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.example.common.listener.DictListener;
import com.example.common.service.DictService;
import com.example.common.util.exception.BaseException;
import com.example.common.util.utils.DateUtils;
import com.example.common.util.utils.StringUtils;
import com.example.model.domain.entity.common.Dict;
import com.example.model.vo.common.DictExcelVo;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.example.common.mapper.DictMapper;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 数据字典Service业务层处理
 *
 * @author ruoyi
 * @date 2021-07-10
 */
@Service
public class DictServiceImpl implements DictService
{
    @Autowired
    private DictMapper dictMapper;



    /**
     * 查询数据字典列表
     *
     * @param dict 数据字典
     * @return 数据字典
     */
    @Override
    public List<Dict> selectDictList(Dict dict)
    {
        return dictMapper.selectDictList(dict);
    }


    /**
     * 批量删除数据字典
     *
     * @param ids 需要删除的数据字典ID
     * @return 结果
     */
    @Override
    public int deleteDictByIds(Long[] ids)
    {
        return dictMapper.deleteDictByIds(ids);
    }


    @Override
    public String getDictName(String dictCode, String value) {
        if (StringUtils.isEmpty(dictCode)){
            return dictMapper.selectDictByValue(value);
        }else {
            return dictMapper.selectDictByDictCodeValue(dictCode, value);
        }
    }

    /**
     * 根据数据id查询子数据列表
     * @param id
     * @return
     */
    @Cacheable(value = "dict")
    @Override
    public List<Dict> getChildDataById(Long id) {
        List<Dict> dicts = dictMapper.selectDictByParentId(id);
        dicts.forEach(dict -> dict.setHasChildren(this.isChildren(dict.getParentId())));
        return dicts;
    }

    /**
     * 根据dictCode获取下级节点
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> getDictByDictCode(String dictCode) {
        Long id = dictMapper.getDictByDictCode(dictCode);
        return this.getChildDataById(id);
    }


    @CacheEvict(value = "dict", allEntries = true)
    @Override
    public Boolean importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictExcelVo.class, new DictListener()).sheet().doRead();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            throw new BaseException("common","导入数据失败");
        }
    }


    @Override
    public byte[] exportDict(HttpServletResponse response) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
        List<Dict> dicts = dictMapper.selectDictList(null);
        ArrayList<DictExcelVo> dictExcelVos = new ArrayList<>();
        dicts.forEach(dict -> {
            DictExcelVo dictExcelVo = new DictExcelVo();
            BeanUtils.copyProperties(dict,dictExcelVo);
            dictExcelVos.add(dictExcelVo);
        });
        try {
            zipOutputStream.putNextEntry(new ZipEntry("dict"));
            IOUtils.write(dictExcelVos.toString(),zipOutputStream, Constants.UTF_8);
            zipOutputStream.flush();
            zipOutputStream.closeEntry();
            IOUtils.closeQuietly(zipOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toByteArray();
    }


    private boolean isChildren(Long id){
        Integer integer = dictMapper.selectDictCountById(id);
        return integer>0;
    }


}
